package website.lhc.adminsystem.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import website.lhc.admincommo.constant.SessionConstant;
import website.lhc.adminsystem.dto.LoginDto;
import website.lhc.adminsystem.entity.UserInfo;
import website.lhc.adminsystem.mapper.UserInfoMapper;
import website.lhc.adminsystem.service.IUserInfoService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static website.lhc.admincommo.util.Assert.notNull;
import static website.lhc.admincommo.util.Assert.stat;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 582895699@qq.com
 * @since 2021-02-08
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo userLogin(LoginDto dto, HttpServletRequest request, HttpServletResponse response) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getAccount, dto.getUserName());
        UserInfo currentUser = userInfoMapper.selectOne(queryWrapper);
        notNull(currentUser, "用户名或密码错误");
        Boolean deleted = currentUser.getIsDelete();
        stat(deleted, "该账号已被注销");
        Boolean enable = currentUser.getEnable();
        stat(enable, "该账户已被冻结");
        String pwd = SecureUtil.sha1(dto.getPassword() + currentUser.getSalt());
        stat(!pwd.equals(currentUser.getPassword()), "用户名或密码错误");

        HttpSession session = request.getSession(true);
        session.setAttribute(dto.getUserName(), currentUser.toString());

        Cookie cookie = new Cookie(SessionConstant.COOKIE_NAME, dto.getUserName());
        cookie.setMaxAge(SessionConstant.COOKIE_TIME_OUT);
        cookie.setPath("/");
        cookie.setSecure(true);
        response.addCookie(cookie);
        return currentUser;
    }
}
